package com.beijiteshop.shop.ui.login

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.beijiteshop.libcommon.base.activity.BaseActivity
import com.beijiteshop.shop.R
import com.beijiteshop.shop.databinding.ActivityLoginBinding
import com.beijiteshop.shop.ui.login.vm.UserVM
import com.beijiteshop.shop.ui.main.MainActivity
import com.beijiteshop.shop.wxapi.WXHelper
import com.blankj.utilcode.util.ActivityUtils
import org.koin.android.viewmodel.ext.android.viewModel

/**
 * 登录页面
 */
@Route(path = "/login/login")
class LoginActivity : BaseActivity<ActivityLoginBinding>(){

    private val mUserVM: UserVM by viewModel()

    private var mPhoneStr: String? = null
    private var mCodeStr: String? = null
    private var mIsCountDown = false

    private var mCountDownTimer: CountDownTimer? = null

    /**
     * 是否将其它activity移除栈
     */
    @Autowired(name = "finishOther")
    @JvmField
    var mIsFinishOthers: Boolean = false

    override fun getLayoutRes(): Int = R.layout.activity_login

    override fun initView(savedInstanceState: Bundle?) {
        ARouter.getInstance().inject(this)
        setLoginBtnEnable()
        setCodeBtnEnable()
    }

    override fun initData() {
        if (mIsFinishOthers){
            ActivityUtils.finishOtherActivities(this::class.java)
        }
    }

    override fun initEvent() {
        startObserve()

        mBinding.loginBackIv.setOnClickListener {
            finish()
        }

        mBinding.loginPhoneEt.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                setLoginBtnEnable()
                setCodeBtnEnable()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        mBinding.loginCodeEt.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable?) {
                setLoginBtnEnable()
                setCodeBtnEnable()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })

        mBinding.loginGetCodeBtn.setOnClickListener {
            if (!mPhoneStr.isNullOrEmpty()){
                showLoading()
                mUserVM.getSmsCode(mPhoneStr!!)
            }
        }

        mBinding.loginBtn.setOnClickListener {
            if (mPhoneStr.isNullOrEmpty() || mCodeStr.isNullOrEmpty()){
                showToast(resources.getString(R.string.please_input_phone_and_code))
            }else{
                showLoading(resources.getString(R.string.logging))
                mUserVM.login(mPhoneStr!!,mCodeStr!!)
            }
        }

        mBinding.loginWechatIv.setOnClickListener {
            wxLogin()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mCountDownTimer?.cancel()
    }

    private fun startObserve(){
        mUserVM.liveSmsCode.observeKt {
            hideLoading()
            showToast(resources.getString(R.string.verification_code_sent))
            startCountDown()
        }

        mUserVM.liveLogin.observeKt { token ->
            hideLoading()
            showToast(resources.getString(R.string.login_success))
            startToMain()
            finish()
        }

        mUserVM.liveNetError.observeKt {
            hideLoading()
            showToast(it?:resources.getString(R.string.state_network_error))
        }
        mUserVM.liveError.observeKt {
            hideLoading()
            showToast(it?:resources.getString(R.string.something_error))
        }
    }

    private fun setLoginBtnEnable(){
        mPhoneStr = mBinding.loginPhoneEt.text?.toString()
        mCodeStr = mBinding.loginCodeEt.text?.toString()
        mBinding.loginBtn.isEnabled = !mPhoneStr.isNullOrEmpty() && !mCodeStr.isNullOrEmpty()
    }

    private fun setCodeBtnEnable(){
        mPhoneStr = mBinding.loginPhoneEt.text?.toString()
        mBinding.loginGetCodeBtn.isEnabled = !mPhoneStr.isNullOrEmpty() && !mIsCountDown
    }

    private fun startCountDown(){
        if (mCountDownTimer == null){
            mCountDownTimer = object : CountDownTimer(60*1000,1000){
                override fun onFinish() {
                    mIsCountDown = false
                    mBinding.loginGetCodeBtn.text = resources.getString(R.string.get_verification_code)
                    setCodeBtnEnable()
                }

                override fun onTick(millisUntilFinished: Long) {
                    mIsCountDown = true
                    mBinding.loginGetCodeBtn.isEnabled = false
                    mBinding.loginGetCodeBtn.text = "${(millisUntilFinished/1000f).toInt()}s"
                }
            }
        }
        mCountDownTimer?.start()
    }

    private fun startToMain(){
        val intent = Intent(this,MainActivity::class.java)
        startActivity(intent)
    }

    /**
     * 微信登录
     */
    private fun wxLogin(){
        if (WXHelper.getInstance().isWXInstalled()){
            WXHelper.getInstance().login()
        }else{
            showToast(resources.getString(R.string.please_install_wx_app))
        }
    }
}